﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;

namespace ChangeName
{
    public partial class ChangeName : Form
    {
        public ChangeName()
        {
            InitializeComponent();
            com_order.SelectedIndex = 0;
        }

        private void btn_path_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                txt_path.Text = dialog.SelectedPath;
                string[] filenames = Directory.GetFiles(txt_path.Text);
                UpdateDataSource(filenames, com_order.SelectedIndex == 0);
            }
        }

        private void UpdateDataSource(string[] files, bool isDesc)
        {
            list_Name.Items.Clear();
            if (files.Length == 0)
                return;
            if (isDesc)
                Array.Sort(files, new FileNameComparerAsc());
            else if(com_order.SelectedIndex!=2)
                Array.Sort(files, new FileNameComparerDesc());
            for (int i = files.Length - 1; i >= 0; i--)
            {
                ListViewItem item = new ListViewItem(new string[] { (files.Length - i).ToString(), Path.GetFileName(files[i]), "" });
                list_Name.Items.Add(item);
            }
        }

        private void com_order_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (Directory.Exists(txt_path.Text))
            {
                string[] filenames = Directory.GetFiles(txt_path.Text);
                UpdateDataSource(filenames, com_order.SelectedIndex == 0);
            }
        }

        private void btn_change_Click(object sender, EventArgs e)
        {
            if (list_Name.SelectedItems.Count > 0)
            {
                NewNameForm form = new NewNameForm();
                form.NewName = RemoveNumberInStr(list_Name.SelectedItems[0].SubItems[2].Text);
                if (form.ShowDialog() == DialogResult.OK)
                {
                    if (form.IsApplyToAll)
                    {
                        var selectedItems = list_Name.Items;
                        for (int i = 0; i < selectedItems.Count; i++)
                        {
                            if(form.IsForward)
                                selectedItems[i].SubItems[2].Text = form.NewName + selectedItems[i].SubItems[1].Text;
                            else
                                selectedItems[i].SubItems[2].Text = selectedItems[i].SubItems[1].Text.Replace(Path.GetExtension(selectedItems[i].SubItems[1].Text),"") + form.NewName + Path.GetExtension(selectedItems[i].SubItems[1].Text);
                        }
                    }
                    else
                    {
                        var selectedItems = list_Name.SelectedItems;
                        for (int i = 0; i < selectedItems.Count; i++)
                        {
                            selectedItems[i].SubItems[2].Text = form.NewName + (i + 1).ToString() + Path.GetExtension(selectedItems[i].SubItems[1].Text);
                        }
                    }
                }
            }
        }

        private void btn_apply_Click(object sender, EventArgs e)
        {
            FileInfo fileInfo;
            for (int i = 0; i < list_Name.Items.Count; i++)
            {
                if (list_Name.Items[i].SubItems[1].Text != list_Name.Items[i].SubItems[2].Text && list_Name.Items[i].SubItems[2].Text != "")
                {
                    fileInfo = new FileInfo(txt_path.Text + "\\" + list_Name.Items[i].SubItems[1].Text);
                    fileInfo.MoveTo(txt_path.Text + "\\" + list_Name.Items[i].SubItems[2].Text);
                }
            }
        }

        private string RemoveNumberInStr(string str)
        {
            string rst = "";
            for (int i = 0; i < str.Length; i++)
            {
                if (!char.IsNumber(str[i]))
                    rst += str[i].ToString();
            }
            return rst;
        }

        private void btn_save_Click(object sender, EventArgs e)
        {
            SaveFileDialog dialog = new SaveFileDialog();
            if (!Directory.Exists(Application.StartupPath + "\\data"))
                Directory.CreateDirectory(Application.StartupPath + "\\data");
            dialog.InitialDirectory = Application.StartupPath + "\\data";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                FileStream fs = File.Create(dialog.FileName);
                AddText(fs, GetDataSource());
                fs.Dispose();
                MessageBox.Show("save complete!!");
            }
        }

        private void btn_open_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            if (!Directory.Exists(Application.StartupPath + "\\data"))
                Directory.CreateDirectory(Application.StartupPath + "\\data");
            dialog.InitialDirectory = Application.StartupPath + "\\data";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string rst = "";
                using (FileStream fs = File.OpenRead(dialog.FileName))
                {
                    byte[] b = new byte[1024];
                    UTF8Encoding temp = new UTF8Encoding(true);
                    while (fs.Read(b, 0, b.Length) > 0)
                    {
                        rst += temp.GetString(b);
                    }
                }
                LoadDataSource(rst);
            }
        }

        private void AddText(FileStream fs, string value)
        {
            byte[] info = new UTF8Encoding(true).GetBytes(value);
            fs.Write(info, 0, info.Length);
        }

        private string GetDataSource()
        {
            string rst = "";
            for (int i = 0; i < list_Name.Items.Count; i++)
            {
                rst += list_Name.Items[i].SubItems[2].Text + "<++>";
            }
            return rst;
        }

        private void LoadDataSource(string source)
        {
            string[] items = source.Split(new string[] { "<++>" }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < list_Name.Items.Count; i++)
            {
                if (items.Count() == i)
                    return;
                list_Name.Items[i].SubItems[2].Text = items[i];
            }
        }
    }

  
    public class FileNameComparerAsc : IComparer
    {
        public int Compare(object a, object b)
        {
            int i = GetNumberOfName(a.ToString());
            int j = GetNumberOfName(b.ToString());
            return i > j ? 1 : -1;
        }

        public int GetNumberOfName(string name)
        {
            string str = Path.GetFileName(name);
            str = str.Replace(Path.GetExtension(name), "");
            string rst = "";
            for (int i = 0; i < str.Length; i++)
            {
                if(char.IsNumber(str[i]))
                    rst+=str[i];
            }
            return int.Parse(rst);
        }
    }
    public class FileNameComparerDesc : IComparer
    {
        public int Compare(object a, object b)
        {
            int i = GetNumberOfName(a.ToString());
            int j = GetNumberOfName(b.ToString());
            return i < j ? 1 : -1;
        }

        public int GetNumberOfName(string name)
        {
            string str = Path.GetFileName(name);
            str = str.Replace(Path.GetExtension(name), "");
            string rst = "";
            for (int i = 0; i < str.Length; i++)
            {
                if(char.IsNumber(str[i]))
                    rst+=str[i];
            }
            return int.Parse(rst);
        }
    }
}
